package com.houdoudou.customer.me;



import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import com.houdoudou.bean.Customer;
import com.houdoudou.customer.CustomerMainActivity;
import com.houdoudou.customer.R;
import com.houdoudou.customer.common.Constant;
import com.houdoudou.customer.common.TransPasswordUtil;
import com.houdoudou.customer.common.UniversalHttpPost;

import android.app.Activity;
import android.app.Instrumentation;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class LoginAct extends Activity {
    
	ImageButton back;
	Button login,regist,forget;
	EditText tel,secret;
	ProgressBar progres;
	TextView  result;
	View.OnClickListener myOnClickListener;
	String TEL="",SECRET="";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_login);
		init_listener();
		login=(Button) findViewById(R.id.btn_login_act_login);
		regist=(Button) findViewById(R.id.btn_regist_act_login);
		tel= (EditText) findViewById(R.id.et_tel_act_longin);
		secret=(EditText) findViewById(R.id.et_secret_act_longin);
		back=(ImageButton) findViewById(R.id.back_act_login);
		progres= (ProgressBar) findViewById(R.id.prgs_act_login);
		result= (TextView) findViewById(R.id.tv_result_act_login);
		forget= (Button) findViewById(R.id.btn_forget_act_login);
		
		progres.setVisibility(View.GONE);
		result.setVisibility(View.GONE);
		
		back.setOnClickListener(myOnClickListener);
		login.setOnClickListener(myOnClickListener);
		regist.setOnClickListener(myOnClickListener);
		forget.setOnClickListener(myOnClickListener);
	}

	private void init_listener(){
		myOnClickListener= new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(v==back){
					new Thread () { 
						public void run () { 
						try { 									
						Instrumentation inst= new Instrumentation(); 
						inst.sendKeyDownUpSync(KeyEvent. KEYCODE_BACK); 
						} catch(Exception e) { 
						e.printStackTrace(); 
						         } 
						  } 
						}.start();
				 }
				if(v==login){
					
					boolean checkinput=true;
					if(tel.getText().toString().length()!=11){
						checkinput=false;
						Toast.makeText(LoginAct.this, "电话号码位数不对",Toast.LENGTH_SHORT ).show();}
					
					
					if(checkinput){
					  progres.setVisibility(View.VISIBLE);					
						result.setVisibility(View.GONE);
						 regist.setClickable(false);
						 forget.setClickable(false);
						 login.setClickable(false);
						String[] params= new String[5];
			            params[0]=Constant.BaseUrl+Constant.CustomerUrl;
		                params[1]="login"; //PostCod
		                JSONObject jsonData=new JSONObject();			
						  		        
			               jsonData.put(Customer.TELNUM, tel.getText().toString());		
			               try {
							String cipher= TransPasswordUtil.encrypt(secret.getText().toString()); 
							jsonData.put(Customer.SECRET, cipher); } catch (Exception e) {e.printStackTrace();}
			               
			               TEL=tel.getText().toString();
			               SECRET=secret.getText().toString();
			               
			                params[2]=jsonData.toString();
		             new HttpPostTaskforLogin().execute(params);
					}
					
				}
				if(v==regist){
					Intent intent= new Intent(LoginAct.this, RegistAct.class);
					startActivity(intent);
				}
				if(v==forget){
					Intent intent= new Intent(LoginAct.this, ForgetSecretAct.class);
					startActivity(intent);
				}
				
			}
		};
	}
	
	private  class HttpPostTaskforLogin extends android.os.AsyncTask<String,String,Map<String,Object>>{

		

		@Override
		protected Map<String,Object> doInBackground(String... params) {
			// TODO Auto-generated method stub
			 Map<String,Object> map = new HashMap<String ,Object>();		
		  map =	UniversalHttpPost.doPost(params);	             
			return map;
		}
		
		@Override
		protected void onPostExecute(Map<String,Object> map) {
		
			 progres.setVisibility(View.GONE);	
			 regist.setClickable(true);
			 forget.setClickable(true);
			 login.setClickable(true);
			 System.out.println("-----------onPostExecute()--------------");
			 String PostResult=(String) map.get("PostResult");		 
			 boolean networkstate=(Boolean) map.get("PostState");
			 if(!networkstate){
				 result.setVisibility(View.VISIBLE);
				  result.setText("无法连接服务器,");
		      
			}else{
			//	Toast.makeText(getActivity(), "服务器返回数据为"+PostResult, Toast.LENGTH_SHORT).show();
				Boolean success=false;
				String errorInfo="";
				JSONObject json = null;
				
				try{
			     json= JSONObject.fromObject(PostResult);
				 success=json.getBoolean("success");
				 errorInfo=json.getString("errorInfo");	
				}catch(JSONException e){
					 result.setVisibility(View.VISIBLE);
					  result.setText("数据解析错误");
				}
										   												      		       
		       if(success){     
		    	   Constant.customerJO=json.getJSONObject("customer");
		    	  
		    	   SharedPreferences sharedPreferences = LoginAct.this.getSharedPreferences("config", Context.MODE_PRIVATE);
		 		   Editor editor = sharedPreferences.edit();   
		 		   editor.putString("customer",Constant.customerJO.toString());
		 		 //  editor.putString("Customer_Telnum",Constant.Customer_Telnum ); 
		    	  //  editor.putString("Customer_Secret", Constant.Customer_Secret);
		    	   editor.commit();		    	 
				   LoginAct.this.finish(); 	 		    	   
		    	
		             }else{
		            	 result.setVisibility(View.VISIBLE);
		            	 result.setText(errorInfo); 
		             } 			
		  		         
				  }// if 网络正常结束
			
		} //onPostExecute
	} //AsyncTask
	
}
